package com.dsg.kf.common.util;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Random;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;

public class FileUploadUtil {
     public static final List<String> ALLOW_TYPES = Arrays.asList(
                "image/jpg","image/jpeg","image/png","image/gif"
        );
    //文件重命名
        public static String rename(String fileName){
            int i = fileName.lastIndexOf(".");
            String str = fileName.substring(i);
            return new Date().getTime()+""+ new Random().nextInt(99999999) +str;
        }
    //校验文件类型是否是被允许的
        public static boolean allowUpload(String postfix){
            return ALLOW_TYPES.contains(postfix);
        }
        
        /**
    	 * 上传文件
    	 * 
    	 * @param fileRealPath
    	 * @param uploadFile
    	 * @return
    	 */
    	public static boolean saveAudioFile(byte[] multFilebyte, String basePath, String name) throws IOException {
    		String filePath = FilenameUtils.concat(basePath, name);
    		/**
    		 * 上传原图
    		 */
    		File file = new File(filePath);
    		FileOutputStream bigfs = FileUtils.openOutputStream(file);
    		bigfs.write(multFilebyte);
    		bigfs.close();
    		return true;
    	}
    	
    	

        /**
    	 * 上传Img文件2
    	 * 
    	 * @param basePath
    	 * @param multFilebyte
    	 * @return
    	 */
    	public static String uploadImgFile(byte[] multFilebyte, String basePath, String contype,String originName, String path) throws IOException {
    		String fileName = null;
    		if (FileUploadUtil.allowUpload(contype)) {
				fileName = FileUploadUtil.rename(originName);
				basePath=basePath.concat(path);
				File dir = new File(basePath);
				if (!dir.exists()) {
					dir.mkdirs();
				}
				FileUploadUtil.saveAudioFile(multFilebyte, basePath, fileName);
			}
    		return fileName;
    	}
}